package com.efounder.model;

import android.app.Activity;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.pm.PackageInfo;
import android.graphics.Color;
import android.os.Handler;
import android.os.Message;
import android.view.View;
import android.widget.Toast;

import com.core.xml.StubObject;
import com.efounder.chat.model.Constant;
import com.efounder.constant.EnvironmentVariable;
import com.efounder.eai.data.JResponseObject;
import com.efounder.ospmobilelib.R;
import com.efounder.util.AbAppUtil;
import com.efounder.util.AppContext;
import com.efounder.util.FileDeleteUtil;
import com.efounder.util.LoadingDataUtilBlack;
import com.efounder.util.ToastUtil;
import com.efounder.utils.ProgressDialogForUpdate;
import com.efounder.utils.ResStringUtil;
import com.efounder.view.NewVersionAlertDialog;
import com.utilcode.util.AppUtils;
import com.zhuiji7.filedownloader.download.DownLoadListener;
import com.zhuiji7.filedownloader.download.DownLoadManager;
import com.zhuiji7.filedownloader.download.DownLoadService;
import com.zhuiji7.filedownloader.download.dbcontrol.FileHelper;
import com.zhuiji7.filedownloader.download.dbcontrol.bean.SQLDownLoadInfo;

import org.greenrobot.eventbus.EventBus;

import java.io.File;
import java.util.Hashtable;
import java.util.Map;
import java.util.Timer;
import java.util.TimerTask;

import static com.efounder.chat.model.Constant.AndroidApkPath;
import static com.efounder.forwechat.BaseApp.context;
import static com.efounder.frame.utils.Constants.KEY_SETTING_APPID;
import static com.efounder.frame.utils.Constants.KEY_SETTING_DEFAULT_SERVER_ADDRESS;
import static com.efounder.frame.utils.Constants.KEY_SETTING_DEFAULT_SERVER_HTTP_TYPE;
import static com.efounder.frame.utils.Constants.KEY_SETTING_DEFAULT_SERVER_PATH;
import static com.efounder.frame.utils.Constants.KEY_SETTING_DEFAULT_SERVER_PORT;

/**
 * on 2016/8/25 0025.
 */

public class APKUpdateManager {

    private String TAG = "APKUpdateManager";
    private CheckAppVersionUtilInterface checkAppVersionUtilInterface;
    /*使用DownLoadManager时只能通过DownLoadService.getDownLoadManager()的方式来获取下载管理器，不能通过new DownLoadManager()的方式创建下载管理器*/
    private DownLoadManager manager;
    String apkDownUrl = "";
    private static float lastScale, nowScale;
    private static boolean isPaused = false;
    //TaskInfo info = new TaskInfo();
    private String versionLast;

    public APKUpdateManager() {
    }

    /**
     * @param version
     * @return
     */
    public boolean checkIsNeedToDown(String version) {
        versionLast = version;
        PackageInfo pi = AbAppUtil.getPackageInfo(AppContext.getInstance());
        if (!version.equals(pi.versionName)) {
            //清除上一个版本的apk
            String fileLocation = FileHelper.getBaseFilePath() + pi.versionName;
            FileHelper.DeleteFolder(fileLocation);

            return true;
        } else {
            return false;
        }
    }

    /**
     * 检查是否需要强制升级
     *
     * @param version
     * @return
     */
    public boolean checkIsNeedForceDown(String version) {

        PackageInfo pi = AbAppUtil.getPackageInfo(AppContext.getInstance());
        if (version.equals(pi.versionName)) {
            return false;
        }
        String[] versions = version.split("\\.");
        String[] localVersions = pi.versionName.split("\\.");
        if (localVersions != null && localVersions.length == 3 && versions != null && versions.length == 3) {
            if (!versions[0].equals(localVersions[0])) {//版本号第一位不相同，强制升级
                return true;
            }
            if (!versions[1].equals(localVersions[01])) {//版本号第2位不相同，强制升级
                return true;
            }

        }

        return false;


    }

    /**
     * 初始化下载服务
     *
     * @param
     */
    public void start(String _apkDownUrl, CheckAppVersionUtilInterface _checkAppVersionUtilInterface) {
        apkDownUrl = _apkDownUrl;
        checkAppVersionUtilInterface = _checkAppVersionUtilInterface;
        startDownLoad();
    }

    private void startDownLoad() {
            /*获取下载管理器*/
            manager = DownLoadService.getDownLoadManager();

            if (manager == null){
                return;
            }

            /*设置用户ID，客户端切换用户时可以显示相应用户的下载任务*/
            PackageInfo pi = AbAppUtil.getPackageInfo(AppContext.getInstance());
            manager.changeUser(versionLast);
            //FileHelper.setUserID(pi.versionName);
            /*断点续传需要服务器的支持，设置该项时要先确保服务器支持断点续传功能*/
            manager.setSupportBreakpoint(true);
            manager.setCurrentTask(Constant.ApkFileName);
            /*服务器一般会有个区分不同文件的唯一ID，用以处理文件重名的情况*/
            //info.setFileName(Constant.ApkFileName);
            //info.setTaskID(Constant.ApkFileName);

            //info.setOnDownloading(true);
             /*将任务添加到下载队列，下载器会自动开始下载*/
            int i = manager.addTask(Constant.ApkFileName, apkDownUrl, Constant.ApkFileName);

            final Timer timerFresh = new Timer();
            timerFresh.schedule(new TimerTask() {
                public void run() {
                    if (lastScale == nowScale && !isPaused && nowScale != 0) {
                        downErrorHandler.sendEmptyMessage(0);
                        //  Toast.makeText(context, "网络不稳定，请稍后再试，或者点击进度条双击右边按钮", 200).show();
                    }
                    nowScale = lastScale;
                    if ((int) (lastScale * 100) == 100)
                        timerFresh.cancel();
                }
            }, 1000, 10000);

            manager.setSingleTaskListener(Constant.ApkFileName, new DownLoadListener() {
                @Override
                public void onStart(SQLDownLoadInfo sqlDownLoadInfo) {
                }

                @Override
                public void onProgress(SQLDownLoadInfo sqlDownLoadInfo, boolean isSupportBreakpoint) {
                    //info.setDownFileSize(sqlDownLoadInfo.getDownloadSize());
                    //info.setFileSize(sqlDownLoadInfo.getFileSize());

                    float lastScale = (float) sqlDownLoadInfo.getDownloadSize() / sqlDownLoadInfo.getFileSize();
                    Message message = new Message();
                    message.arg1 = (int) (lastScale * 100);
                    downProgressHandler.sendMessage(message);//发送message信息

                }

                @Override
                public void onStop(SQLDownLoadInfo sqlDownLoadInfo, boolean isSupportBreakpoint) {
                    checkAppVersionUtilInterface.stop();
                }

                @Override
                public void onError(SQLDownLoadInfo sqlDownLoadInfo) {
                    //如果出现其他类型的异常，会删除这条任务及cache文件，并重新启动任务,增加延时重新请求数据的功能。
                    try {
                        Thread.sleep(3000);
                        manager.deleteTask(Constant.ApkFileName);
                        manager.addTask(Constant.ApkFileName, apkDownUrl, Constant.ApkFileName);
                        //info.setOnDownloading(true);
                        manager.setSingleTaskListener(Constant.ApkFileName, this);
                        manager.startTask(manager.getCurrentTask());
                    } catch (Exception e) {
                    }
                    checkAppVersionUtilInterface.error();
                }

                @Override
                public void onSuccess(SQLDownLoadInfo sqlDownLoadInfo) {
                    AppContext.getInstance().stopService(new Intent(AppContext.getInstance(), DownLoadService.class));
                    final String TEMP_FILEPATH = FileHelper.getFileDefaultPath();
                    String filePath = TEMP_FILEPATH + "/(" + FileHelper.filterIDChars(sqlDownLoadInfo.getFileName()) + ")" + sqlDownLoadInfo.getFileName();
                    checkAppVersionUtilInterface.downloadOver(filePath);
                }

                @Override
                public void onNetError(SQLDownLoadInfo sqlDownLoadInfo) {
                    try {
                        Thread.sleep(3000);
                        manager.startTask(manager.getCurrentTask());
                    } catch (Exception e) {

                    }
                }
            });
            //如果已经下载完毕
            if (i == -1) {
                final String TEMP_FILEPATH = FileHelper.getFileDefaultPath();
                String filePath = TEMP_FILEPATH + "/(" + FileHelper.filterIDChars(Constant.ApkFileName) + ")" + Constant.ApkFileName;
                checkAppVersionUtilInterface.downloadOver(filePath);
            } else {
                //info.setOnDownloading(true);
                manager.startTask(Constant.ApkFileName);
            }
        }

    public void stopTask() {
        //info.setOnDownloading(false);
        if (manager != null)
            manager.stopTask(Constant.ApkFileName);
        isPaused = true;
        AppContext.getInstance().stopService(new Intent(AppContext.getInstance(), DownLoadService.class));

    }

    public void startTask() {
        //info.setOnDownloading(true);
        if (manager != null)
            manager.startTask(Constant.ApkFileName);
        isPaused = false;
    }

    private Handler downErrorHandler = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            super.handleMessage(msg);
            Toast.makeText(context, R.string.common_text_network_error, Toast.LENGTH_SHORT).show();
        }
    };
    private Handler downProgressHandler = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            super.handleMessage(msg);
            checkAppVersionUtilInterface.updateProgress(msg.arg1);
        }
    };


    /**
     * 检查是否需要升级apk，如果需要弹框升级，由弹框控制是否在下载
     *
     * @param mContext
     * @param ro
     * @param mHandler 响应 更新xml资源 更新界面操作
     * @return
     */
    public boolean CheckAPKVerion(Context mContext, final JResponseObject ro, Handler mHandler) {
        Map<?, ?> responseMap = ro.getResponseMap();
        JResponseObject pingtaiRO = (JResponseObject) responseMap.get("pingtai");
        Map<?, ?> pingtaiResponseMap = pingtaiRO.getResponseMap();
        final Map<?, ?> resource = (Map<?, ?>) pingtaiResponseMap.get(Constant.Resource_Key);
        if (resource == null) {
            return false;
        }
        StubObject apkUpdateMap = (StubObject) resource.get(EnvironmentVariable.getProperty(KEY_SETTING_APPID));
        Hashtable<?, ?> htApkUpdate = apkUpdateMap.getStubTable();

        String apkVersionFromServer = (String) htApkUpdate
                .get(Constant.AndroidVersion_Key);

        String apkDownUrl = (String) htApkUpdate.get(AndroidApkPath);

        String appUpdateNote = (String) htApkUpdate.get("APPUpdateNote");

        final APKUpdateManager apkUpdateManager = new APKUpdateManager();
        boolean isNeedUpdateApk = apkUpdateManager.checkIsNeedToDown(apkVersionFromServer);
        boolean isForceUpdateApk = apkUpdateManager.checkIsNeedForceDown(apkVersionFromServer);//是否需要强制升级
        if (isNeedUpdateApk) {
            LoadingDataUtilBlack.dismiss();
//            downAPKInterface.downAPK(mContext,ro, appUpdateNote, apkDownUrl, apkUpdateManager,mHandler);
            downAPK(mContext, ro, appUpdateNote, apkDownUrl, apkUpdateManager, isForceUpdateApk, mHandler);
        } else {
            LoadingDataUtilBlack.dismiss();
            //检查资源文件更新
            boolean isNeedUpdateRES = CheckRESVerion(mContext, ro, mHandler);

        }
        return isNeedUpdateApk;
    }

    /**
     * APP下载
     *
     * @param appUpdateNote 更新说明
     * @param apkDownUrl    下载路径
     * @param isForceUpdate 是否强制升级
     */
    public void downAPK(final Context mContext, final JResponseObject ro, String appUpdateNote, final String apkDownUrl, final APKUpdateManager apkUpdateManager, final boolean isForceUpdate, final Handler mHandler) {
        String appDownUIVersion = EnvironmentVariable.getProperty("appDownUIVersion", "0");
        if ("0".equals(appDownUIVersion)) {
            //如果是老样式
            downapp1(mContext, ro, appUpdateNote, apkDownUrl, apkUpdateManager, isForceUpdate, mHandler);
            return;
        }

        //新样式

        String note = "";
        if (appUpdateNote != null) {
            note = appUpdateNote.replace(";", "\n");
        }
        final NewVersionAlertDialog newVersionAlertDialog = new NewVersionAlertDialog((Activity) mContext);
        newVersionAlertDialog.setTitle(mContext.getResources().getString(R.string.common_text_app_update));
        newVersionAlertDialog.setTextInfo(note);
        //设置中途不可暂停
        newVersionAlertDialog.setCanPause(false);
        newVersionAlertDialog.show();
        newVersionAlertDialog.setCanCancle(!isForceUpdate);

        newVersionAlertDialog.setListener(new NewVersionAlertDialog.UploadListener() {
            @Override
            public void onBegin() {
                beginDownLoadApk(apkUpdateManager, newVersionAlertDialog, mContext, apkDownUrl);
                // Toast.makeText(context, "出现异常。正在重试", Toast.LENGTH_LONG).show();
            }

            @Override
            public void onPause() {

            }

            @Override
            public void onCancle() {
                apkUpdateManager.stopTask();
                newVersionAlertDialog.dismiss();
                if (ro != null)
                    CheckRESVerion(mContext, ro, mHandler);
            }

            @Override
            public void onResume() {

            }
        });

        if (1 == 1) {
            return;
        }

     /*   final ProgressDialogForUpdate progressDialogForUpdate = new ProgressDialogForUpdate(mContext, note, "应用升级", "立即下载", "取消");

        progressDialogForUpdate.showDialog();
        if (isForceUpdate) {
            progressDialogForUpdate.getDialogBuild().getNegativeButton().setVisibility(View.GONE);
            progressDialogForUpdate.getDialogBuild().getNegativeButton().setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    ToastUtil.showToast(mContext, "此版本必须更新后才能使用");
                }
            });
            progressDialogForUpdate.getDialogBuild().getDialog().setCancelable(false);
            progressDialogForUpdate.getDialogBuild().getDialog().setCanceledOnTouchOutside(false);
        }
        progressDialogForUpdate.setOnDiaLogListener(new ProgressDialogForUpdate.OnDialogListener() {
            @Override
            public void dialogPositiveListener(DialogInterface dialogInterface, int which) {
                progressDialogForUpdate.getPositiveView().setClickable(false);
                progressDialogForUpdate.getPositiveView().setTextColor(Color.parseColor("#A5A5A5"));
                apkUpdateManager.start(apkDownUrl, new CheckAppVersionUtilInterface() {
                    @Override
                    public void startDown(float DownBeginFromPercent) {
                        //由于是由dialog控制是否在下载，而不是由下载控制dialog，所以这个方法是空的。
                    }

                    @Override
                    public void updateProgress(float progress) {
                        progressDialogForUpdate.updateProgress((int) progress);
                    }

                    @Override
                    public void downloadOver(String filePath) {
                        progressDialogForUpdate.dismiss();
                        Intent install = new Intent();
                        install.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
                        install.setAction(Intent.ACTION_VIEW);
                        File downloadFile = new File(filePath);
                        install.setDataAndType(Uri.fromFile(downloadFile), "application/vnd.android.package-archive");
                        mContext.startActivity(install);
                    }

                    @Override
                    public void error() {
                        Toast.makeText(mContext, "出现异常。", Toast.LENGTH_LONG).show();
                    }

                    @Override
                    public void stop() {
                    }
                });
            }

            @Override
            public void dialogNegativeListener(DialogInterface dialogInterface, int which) {
                apkUpdateManager.stopTask();
                progressDialogForUpdate.dismiss();
                if (ro != null)
                    CheckRESVerion(mContext, ro, mHandler);
            }

            @Override
            public void dialogCancelListener() {
                apkUpdateManager.stopTask();
                progressDialogForUpdate.dismiss();
                if (ro != null)
                    CheckRESVerion(mContext, ro, mHandler);
            }
        });*/
    }

    public void downapp1(final Context mContext, final JResponseObject ro, String appUpdateNote, final String apkDownUrl, final APKUpdateManager apkUpdateManager, final boolean isForceUpdate, final Handler mHandler) {

        String note = "";
        if (appUpdateNote != null) {
            note = appUpdateNote.replace(";", "\n");
        }


        final ProgressDialogForUpdate progressDialogForUpdate = new ProgressDialogForUpdate(mContext, note, mContext.getResources().getString(R.string.common_text_app_update),
                mContext.getResources().getString(R.string.common_text_download_now), mContext.getResources().getString(R.string.common_text_cancel));

        progressDialogForUpdate.showDialog();
        if (isForceUpdate) {
            progressDialogForUpdate.getDialogBuild().getNegativeButton().setVisibility(View.GONE);
            progressDialogForUpdate.getDialogBuild().getNegativeButton().setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    ToastUtil.showToast(mContext, R.string.apk_update_control_tip_force_update);
                }
            });
            progressDialogForUpdate.getDialogBuild().getDialog().setCancelable(false);
            progressDialogForUpdate.getDialogBuild().getDialog().setCanceledOnTouchOutside(false);
        }
        progressDialogForUpdate.setOnDiaLogListener(new ProgressDialogForUpdate.OnDialogListener() {
            @Override
            public void dialogPositiveListener(DialogInterface dialogInterface, int which) {
                progressDialogForUpdate.getPositiveView().setClickable(false);
                progressDialogForUpdate.getPositiveView().setTextColor(Color.parseColor("#A5A5A5"));
                apkUpdateManager.start(apkDownUrl, new CheckAppVersionUtilInterface() {
                    @Override
                    public void startDown(float DownBeginFromPercent) {
                        //由于是由dialog控制是否在下载，而不是由下载控制dialog，所以这个方法是空的。
                    }

                    @Override
                    public void updateProgress(float progress) {
                        progressDialogForUpdate.updateProgress((int) progress);
                    }

                    @Override
                    public void downloadOver(String filePath) {
                        progressDialogForUpdate.dismiss();
                        AppUtils.installApp(filePath);
                    }

                    @Override
                    public void error() {
                        Toast.makeText(mContext, R.string.apk_update_control_error, Toast.LENGTH_LONG).show();
                    }

                    @Override
                    public void stop() {
                    }
                });
            }

            @Override
            public void dialogNegativeListener(DialogInterface dialogInterface, int which) {
                apkUpdateManager.stopTask();
                progressDialogForUpdate.dismiss();
                if (ro != null)
                    CheckRESVerion(mContext, ro, mHandler);
            }

            @Override
            public void dialogCancelListener() {
                apkUpdateManager.stopTask();
                progressDialogForUpdate.dismiss();
                if (ro != null)
                    CheckRESVerion(mContext, ro, mHandler);
            }
        });
    }


    private void beginDownLoadApk(APKUpdateManager apkUpdateManager, final NewVersionAlertDialog dialog, final Context context, String apkDownUrl) {
        apkUpdateManager.start(apkDownUrl, new CheckAppVersionUtilInterface() {
            @Override
            public void startDown(float DownBeginFromPercent) {
                //由于是由dialog控制是否在下载，而不是由下载控制dialog，所以这个方法是空的。
            }

            @Override
            public void updateProgress(float progress) {
                dialog.setProgress(progress);
            }

            @Override
            public void downloadOver(String filePath) {
                dialog.dismiss();
                AppUtils.installApp(filePath);
            }

            @Override
            public void error() {
                Toast.makeText(context, R.string.common_text_error_retry, Toast.LENGTH_LONG).show();
            }

            @Override
            public void stop() {

            }
        });
    }


    /**
     * 第三部 判断是否需要升级资源文件
     *
     * @param ro
     * @return
     */
    public boolean CheckRESVerion(Context context, final JResponseObject ro, Handler mHandler) {
        Map<?, ?> responseMap = ro.getResponseMap();
        JResponseObject pingtaiRO = (JResponseObject) responseMap.get("pingtai");
        Map<?, ?> pingtaiResponseMap = pingtaiRO.getResponseMap();

        final Map<?, ?> resource = (Map<?, ?>) pingtaiResponseMap.get(Constant.Resource_Key);
        if (resource == null) {
            return false;
        }
        StubObject so = (StubObject) resource.get(EnvironmentVariable.getProperty(KEY_SETTING_APPID));
        Hashtable<?, ?> ht = so.getStubTable();
        String versionFromServer = (String) ht.get(Constant.RES_KEY_VERSION);
        String resUpdateNote = (String) ht.get("RESUpdateNote");
        //todo yqs 判断服务器是否返回资源文件下载路径，有的话，则使用服务器路径
        String resServerPath = null;
        if (ht.containsKey("androidResPath")) {
            resServerPath = (String) ht.get("androidResPath");
            if ("".equals(resServerPath)
                    || !resServerPath.startsWith("http")) {
                resServerPath = null;
            }

        }

        final RESUpdateManager resUpdateManager = new RESUpdateManager();
        boolean isNeedUpdateRes = resUpdateManager.checkIsNeedToDown(versionFromServer);
        if (isNeedUpdateRes) {
//            downAPPResInterface.downAPPRes(context,resUpdateNote, resUpdateManager,mHandler);
            downAPPRes(context, resUpdateNote, resUpdateManager, resServerPath, mHandler);
        } else {
            if (mHandler != null) {//登陆界面 更新UI跳转
                mHandler.sendEmptyMessage(2);
            }
            // CheckIM(ro);
        }
        return isNeedUpdateRes;

    }


    /**
     * 下载APP资源文件
     *
     * @param resUpdateNote
     * @param resUpdateManager
     */
    public void downAPPRes(final Context mContext, String resUpdateNote,
                           final RESUpdateManager resUpdateManager, final String resServerPath, final Handler mHandler) {
        String appDownUIVersion = EnvironmentVariable.getProperty("appDownUIVersion", "0");
        if ("0".equals(appDownUIVersion)) {
            //如果是老样式
            downAPPRes1(mContext, resUpdateNote, resUpdateManager, resServerPath, mHandler);
            return;
        }
        //新样式
        String note = "";
        if (resUpdateNote != null) {
            note = resUpdateNote.replace(";", "\n");
        }
        final NewVersionAlertDialog newVersionAlertDialog = new NewVersionAlertDialog((Activity) mContext);
        newVersionAlertDialog.setTitle(mContext.getResources().getString(R.string.apk_update_control_update_source));
        newVersionAlertDialog.setTextInfo(note);
        newVersionAlertDialog.setCanCancle(true);
        newVersionAlertDialog.setCanPause(false);
        newVersionAlertDialog.show();
        newVersionAlertDialog.setListener(new NewVersionAlertDialog.UploadListener() {
            @Override
            public void onBegin() {
                String downUrl = EnvironmentVariable.getProperty(KEY_SETTING_DEFAULT_SERVER_HTTP_TYPE) + "://" + EnvironmentVariable.getProperty(KEY_SETTING_DEFAULT_SERVER_ADDRESS) + ":"
                        + EnvironmentVariable.getProperty(KEY_SETTING_DEFAULT_SERVER_PORT) + "/"
                        + EnvironmentVariable.getProperty(KEY_SETTING_DEFAULT_SERVER_PATH) + "/MobileResource/" + EnvironmentVariable.getProperty(KEY_SETTING_APPID)
                        + "/updateAndroidForWeChat.zip";
                if (resServerPath != null && !resServerPath.equals("")) {
                    downUrl = resServerPath;
                }
                beginDownLoadRes(resUpdateManager, downUrl, mContext, newVersionAlertDialog, mHandler);
            }

            @Override
            public void onPause() {

            }

            @Override
            public void onCancle() {
                newVersionAlertDialog.dismiss();
                resUpdateManager.stopTask();
                String path = Constant.appSdcardLocation;
                File ESPMobileForWeChat = new File(path);
                //如果没有基本的配置文件
                boolean isNeedUpdateRES = ESPMobileForWeChat.exists();
                if (!isNeedUpdateRES) {
                    Toast.makeText(mContext, R.string.apk_update_control_tip_update_source, Toast.LENGTH_LONG).show();
                } else {
                    if (mHandler != null) {
                        mHandler.sendEmptyMessage(2);
                    }
                }
            }

            @Override
            public void onResume() {

            }
        });


       /* final ProgressDialogForUpdate progressDialogForUpdate = new ProgressDialogForUpdate(mContext, note, "资源文件升级", "立即下载", "取消");
        progressDialogForUpdate.showDialog();
        progressDialogForUpdate.setOnDiaLogListener(new ProgressDialogForUpdate.OnDialogListener() {
            @Override
            public void dialogPositiveListener(DialogInterface dialogInterface, int which) {
                progressDialogForUpdate.getPositiveView().setClickable(false);
                progressDialogForUpdate.getPositiveView().setTextColor(Color.parseColor("#A5A5A5"));
                String downUrl = EnvironmentVariable.getProperty(KEY_SETTING_DEFAULT_SERVER_HTTP_TYPE) + "://" + EnvironmentVariable.getProperty(KEY_SETTING_DEFAULT_SERVER_ADDRESS) + ":"
                        + EnvironmentVariable.getProperty(KEY_SETTING_DEFAULT_SERVER_PORT) + "/"
                        + EnvironmentVariable.getProperty(KEY_SETTING_DEFAULT_SERVER_PATH) + "/MobileResource/" + EnvironmentVariable.getProperty(KEY_SETTING_APPID)
                        + "/updateAndroidForWeChat.zip";
                if (resServerPath != null && !resServerPath.equals("")) {
                    downUrl = resServerPath;
                }
                resUpdateManager.start(downUrl, new CheckRESUtilInterface() {
                    @Override
                    public void startDown(float DownBeginFromPercent) {
                    }

                    @Override
                    public void updateProgress(float progress) {
                        progressDialogForUpdate.updateProgress((int) progress);
                    }

                    @Override
                    public void downloadOver(String filePath) {
                        progressDialogForUpdate.dismiss();
                        //删除rn的文件夹 yqs
                        FileDeleteUtil.DeleteFolder(Constant.UNZIP_DIR + "/reactnative");
                        LoadingDataUtilBlack.show(mContext, "正在解压");
                        resUpdateManager.unzipAndEncryptFile(filePath);
                    }

                    @Override
                    public void error() {
                        Toast.makeText(mContext, "出现异常。", Toast.LENGTH_SHORT).show();
                    }

                    @Override
                    public void stop() {
                        //Toast.makeText(context, "网络异常，请稍后重试", Toast.LENGTH_SHORT).show();
                    }

                    @Override
                    public void unZIPOVER(String versionFromServer) {
                        //设置新的资源文件版本号
                        mContext.getSharedPreferences("res_version",
                                mContext.MODE_PRIVATE).edit()
                                .putString("res_version", versionFromServer)
                                .commit();
                        Message message = new Message();
                        message.what = 1;
                        mHandler.sendMessage(message);
                        //新增eventbus 通知刷新
                        EventBus.getDefault().post(new RefreshViewEvent(RefreshViewEvent.VIEW_TABOTTOMACTIVITY));
                        LoadingDataUtilBlack.dismiss();
                        // CheckIM(ro);
                    }
                });

            }

            @Override
            public void dialogNegativeListener(DialogInterface dialogInterface, int which) {
                progressDialogForUpdate.dismiss();
                resUpdateManager.stopTask();
                String path = Constant.appSdcardLocation;
                File ESPMobileForWeChat = new File(path);
                //如果没有基本的配置文件
                boolean isNeedUpdateRES = ESPMobileForWeChat.exists();
                if (!isNeedUpdateRES) {
                    Toast.makeText(mContext, "本地资源文件丢失，请更新资源文件。", Toast.LENGTH_LONG).show();
                } else {
                    if (mHandler != null) {
                        mHandler.sendEmptyMessage(2);
                    }
                }
            }

            @Override
            public void dialogCancelListener() {
                resUpdateManager.stopTask();
                progressDialogForUpdate.dismiss();
            }
        });*/
    }

    public void downAPPRes1(final Context mContext, String resUpdateNote,
                            final RESUpdateManager resUpdateManager, final String resServerPath, final Handler mHandler) {
        String note = "";
        if (resUpdateNote != null) {
            note = resUpdateNote.replace(";", "\n");
        }
        final ProgressDialogForUpdate progressDialogForUpdate = new ProgressDialogForUpdate(mContext, note, mContext.getResources().getString(R.string.apk_update_control_update_source),
                mContext.getResources().getString(R.string.common_text_download_now), mContext.getResources().getString(R.string.common_text_cancel));
        progressDialogForUpdate.showDialog();
        progressDialogForUpdate.setOnDiaLogListener(new ProgressDialogForUpdate.OnDialogListener() {
            @Override
            public void dialogPositiveListener(DialogInterface dialogInterface, int which) {
                progressDialogForUpdate.getPositiveView().setClickable(false);
                progressDialogForUpdate.getPositiveView().setTextColor(Color.parseColor("#A5A5A5"));
                String downUrl = EnvironmentVariable.getProperty(KEY_SETTING_DEFAULT_SERVER_HTTP_TYPE) + "://" + EnvironmentVariable.getProperty(KEY_SETTING_DEFAULT_SERVER_ADDRESS) + ":"
                        + EnvironmentVariable.getProperty(KEY_SETTING_DEFAULT_SERVER_PORT) + "/"
                        + EnvironmentVariable.getProperty(KEY_SETTING_DEFAULT_SERVER_PATH) + "/MobileResource/" + EnvironmentVariable.getProperty(KEY_SETTING_APPID)
                        + "/updateAndroidForWeChat.zip";
                if (resServerPath != null && !resServerPath.equals("")) {
                    downUrl = resServerPath;
                }
                resUpdateManager.start(downUrl, new CheckRESUtilInterface() {
                    @Override
                    public void startDown(float DownBeginFromPercent) {
                    }

                    @Override
                    public void updateProgress(float progress) {
                        progressDialogForUpdate.updateProgress((int) progress);
                    }

                    @Override
                    public void downloadOver(String filePath) {
                        progressDialogForUpdate.dismiss();
                        //删除rn的文件夹 yqs
                        FileDeleteUtil.DeleteFolder(Constant.UNZIP_DIR + "/reactnative");
                        LoadingDataUtilBlack.show(mContext, ResStringUtil.getString(R.string.common_text_isunziping));
                        resUpdateManager.unzipAndEncryptFile(filePath);
                    }

                    @Override
                    public void error() {
                        Toast.makeText(mContext, ResStringUtil.getString(R.string.apk_update_control_error), Toast.LENGTH_SHORT).show();
                    }

                    @Override
                    public void stop() {
                        //Toast.makeText(context, "网络异常，请稍后重试", Toast.LENGTH_SHORT).show();
                    }

                    @Override
                    public void unZIPOVER(String versionFromServer) {
                        //设置新的资源文件版本号
                        mContext.getSharedPreferences("res_version",
                                mContext.MODE_PRIVATE).edit()
                                .putString("res_version", versionFromServer)
                                .commit();
                        Message message = new Message();
                        message.what = 1;
                        mHandler.sendMessage(message);
                        //新增eventbus 通知刷新
                        EventBus.getDefault().post(new RefreshViewEvent(RefreshViewEvent.VIEW_TABOTTOMACTIVITY));
                        LoadingDataUtilBlack.dismiss();
                        // CheckIM(ro);
                    }
                });

            }

            @Override
            public void dialogNegativeListener(DialogInterface dialogInterface, int which) {
                progressDialogForUpdate.dismiss();
                resUpdateManager.stopTask();
                String path = Constant.appSdcardLocation;
                File ESPMobileForWeChat = new File(path);
                //如果没有基本的配置文件
                boolean isNeedUpdateRES = ESPMobileForWeChat.exists();
                if (!isNeedUpdateRES) {
                    Toast.makeText(mContext, R.string.apk_update_control_tip_update_source, Toast.LENGTH_LONG).show();
                } else {
                    if (mHandler != null) {
                        mHandler.sendEmptyMessage(2);
                    }
                }
            }

            @Override
            public void dialogCancelListener() {
                resUpdateManager.stopTask();
                progressDialogForUpdate.dismiss();
            }
        });
    }

    private void beginDownLoadRes(final RESUpdateManager resUpdateManager, String downUrl, final Context context, final NewVersionAlertDialog newVersionAlertDialog, final Handler mHandler) {
        resUpdateManager.start(downUrl, new CheckRESUtilInterface() {
            @Override
            public void startDown(float DownBeginFromPercent) {
            }

            @Override
            public void updateProgress(float progress) {
                newVersionAlertDialog.setProgress(progress);
            }

            @Override
            public void downloadOver(String filePath) {
                newVersionAlertDialog.dismiss();
                //删除rn的文件夹 yqs
                FileDeleteUtil.DeleteFolder(Constant.UNZIP_DIR + "/reactnative");
                LoadingDataUtilBlack.show(context, ResStringUtil.getString(R.string.common_text_isunziping));
                resUpdateManager.unzipAndEncryptFile(filePath);
            }

            @Override
            public void error() {
                Toast.makeText(context, ResStringUtil.getString(R.string.apk_update_control_error), Toast.LENGTH_SHORT).show();
            }

            @Override
            public void stop() {
                //Toast.makeText(context, "网络异常，请稍后重试", Toast.LENGTH_SHORT).show();
            }

            @Override
            public void unZIPOVER(String versionFromServer) {
                //设置新的资源文件版本号
                context.getSharedPreferences("res_version",
                        context.MODE_PRIVATE).edit()
                        .putString("res_version", versionFromServer)
                        .commit();
                Message message = new Message();
                message.what = 1;
                mHandler.sendMessage(message);
                //新增eventbus 通知刷新
                EventBus.getDefault().post(new RefreshViewEvent(RefreshViewEvent.VIEW_TABOTTOMACTIVITY));
                LoadingDataUtilBlack.dismiss();
                // CheckIM(ro);
            }
        });
    }

//    public interface DownAPPResInterface {
//        public void downAPPRes(Context mContext,String resUpdateNote, RESUpdateManager resUpdateManager, Handler mHandler);
//    }
//     private DownAPPResInterface downAPPResInterface;
//
//    public void setDownAPPResInterface(DownAPPResInterface downAPPResInterface) {
//        this.downAPPResInterface = downAPPResInterface;
//    }
//
//    public interface  DownAPKInterface{
//        public void downAPK(Context mContext,JResponseObject ro, String appUpdateNote,String apkDownUrl,APKUpdateManager apkUpdateManager,Handler mHandler);
//    }
//
//    public void setDownAPKInterface(DownAPKInterface downAPKInterface) {
//        this.downAPKInterface = downAPKInterface;
//    }
//
//    private DownAPKInterface downAPKInterface;
}



